package com.lifeng.security;

import com.lifeng.bean.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Created by lifeng on 2019/8/12.
 * 辅助工具类
 */
public class SpringSecurityUtil {

    /**获取当前用户*/
    public static <T extends MySecurityUser> T getCurrentUser(){
        Object principal = getAuthentication().getPrincipal();
        if (!(principal instanceof MySecurityUser)) {
            return null;
        }
        return (T) principal;
    }

    /**获取真实用户信息*/
    public static User getRealUser(){
        Object principal = getAuthentication().getPrincipal();
        if (!(principal instanceof MySecurityUser)) {
            return null;
        }
        return ((MySecurityUser) principal).getUser();
    }

    /**获取当前用户*/
    public static String getCurrentUserName(){
        String name = getAuthentication().getName();
        if(name == null || "".equals(name)){
            return "";
        }
        return name;
    }

    /**
     * 取得Authentication, 如当前SecurityContext为空时返回null.
     */
    private static Authentication getAuthentication() {
        SecurityContext context = SecurityContextHolder.getContext();
        if (context == null) {
            return null;
        }
        return context.getAuthentication();
    }
}
